<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img :src="imageUrl || defaultImg" class="avatar">
      <!-- <i v-if="!imageUrl" class="el-icon-plus avatar-uploader-icon" /> -->
    </el-upload>
    <el-progress
      v-if="showProgress"
      type="circle"
      :percentage="percent"
      class="progress"
    />
  </div>
</template>

<script>
import defaultImg from '@/assets/404_images/404.png'
export default {
  name: 'UploadImg',
  props: {
    imageUrl: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      percent: 0, // 上传进度
      showProgress: false, // 是否展示进度条
      defaultImg
    }
  },
  methods: {
    async upload(res) {
      // 下面的代码是固定写法
      const COS = require('cos-js-sdk-v5')
      // 填写自己腾讯云cos中的key和id (密钥)
      const cos = new COS({
        SecretId: 'AKIDWrwlKciX5MM5XicFciX5MN7amiNkqgGa', // 身份识别ID
        SecretKey: '4rOdbIkunPlpc8MK1RZR2MPBguqVu1rP' // 身份秘钥
      })
      if (res.file) {
        // 显示进度条
        this.showProgress = true
        const timeout = (ms) => new Promise((res) => setTimeout(res, ms))

        // 执行上传操作
        await cos.putObject(
          {
            Bucket: 'web68-1308713059' /* 存储桶 */,
            Region: 'ap-nanjing' /* 存储桶所在地域，必须字段 */,
            Key: res.file.name /* 文件名 */,
            StorageClass: 'STANDARD', // 上传模式, 标准模式
            Body: res.file, // 上传文件对象
            onProgress: (progressData) => {
              // console.log(JSON.stringify(progressData))
              this.percent = progressData.percent * 100
            }
          },
          async(err, data) => {
            await timeout(2000)
            // 隐藏进度条
            this.showProgress = false
            console.log(err || data)
            // 上传成功之后
            if (data.statusCode === 200) {
              // this.imageUrl = `https:${data.Location}`
              this.$emit('dd', `https:${data.Location}`)
            }
          }
        )
      }
    },
    handleAvatarSuccess(res, file) {
      this.$emit('xx', URL.createObjectURL(file.raw))
      // this.imageUrl =
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
[class^='el-icon-'] {
  line-height: 6 !important;
}
/* .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #fff;
} */
</style>
